package com.buaa.rental.Controller;

import com.buaa.rental.Dao.Application;
import com.buaa.rental.Dao.CommonRep;
import com.buaa.rental.Dao.Home;
import com.buaa.rental.Dao.User;
import com.buaa.rental.Service.ApplicationService;
import com.buaa.rental.Service.HomeService;
import com.buaa.rental.Service.UserService;
import com.buaa.rental.Util.CodeException;
import com.buaa.rental.Util.MyAnnotations.Authorization;
import com.buaa.rental.Util.MyAnnotations.CurrentUser;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api/application")
public class ApplicationController
{

	@Autowired
	private ApplicationService applicationService;

	@Autowired
	private HomeService homeService;

	@Autowired
	private UserService userService;

	@Authorization
	@GetMapping("getAll")
	public CommonRep getAllAppByUer(@CurrentUser User user)
	{
		CommonRep rep = new CommonRep();
		List<Application> apps = applicationService.findByUser(user.uid);
		rep.setData(apps);
		return rep;
	}

	@Authorization
	@GetMapping("getById/{aid}")
	public CommonRep getById(@CurrentUser User user, @PathVariable("aid") long aid)
			throws CodeException
	{
		CommonRep rep = new CommonRep();
		Application app = applicationService.findById(aid);
		if (app.uid != user.uid)
		{
			throw new CodeException("111", "权限错误");
		}
		rep.setData(app);
		return rep;
	}

	@GetMapping("getContractData/{aid}")
	public CommonRep getContractData(@CurrentUser User user, @PathVariable("aid") long aid)
		throws CodeException{
		CommonRep rep = new CommonRep();
		Application app = applicationService.findById(aid);
		if (app.uid != user.uid)
		{
			throw new CodeException("111", "权限错误");
		}
		Map<String,String> map = new HashMap<>();

		map.put("houseAddr",homeService.findById(app.hid).address);
		map.put("userName",user.name);

		rep.setData(map);
		return rep;
	}

	@PostMapping("getExtra")
	public CommonRep getExtra(@RequestBody Map<String, String> inmap) {
		long aid = Integer.parseInt(inmap.get("aid"));
		Map<String, String> map = new HashMap<>();
		Application application = applicationService.findById(aid);
		map.put("customerName", userService.getUserByUid(application.uid).name);
		map.put("houseName", homeService.findById(application.hid).title);
		CommonRep rep = new CommonRep();
		rep.setData(map);
		return rep;
	}
}
